﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;

namespace homework5
{
    class Cal
    {
        private Stack<char> chars = new Stack<char>();
        private Stack<double> nums = new Stack<double>();

        public string getResult(String s)
        {
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] >= 48 && s[i] <= 57)
                {
                    string tem = "";
                    tem += s[i];
                    while (i + 1 < s.Length && ((s[i + 1] >= 48 && s[i + 1] <= 57) || s[i + 1] == '.'))
                    {
                        i++;
                        tem += s[i];
                    }
                    nums.Push(double.Parse(tem));
                }
                else if (s[i] == '*' || s[i] == '/')
                    chars.Push(s[i]);
                else if (s[i] == '+')
                {
                    while (chars.Count > 0)
                    {
                        if (!Operate(chars.Pop()))
                        {
                            return "ERROR";
                        }
                    }
                    chars.Push(s[i]);
                }
                else if (s[i] == '-') {
                    if (i==0)
                    {
                        string tem = "";
                        tem += s[i];
                        while (i + 1 < s.Length && ((s[i + 1] >= 48 && s[i + 1] <= 57) || s[i + 1] == '.'))
                        {
                            i++;
                            tem += s[i];
                        }
                        nums.Push(double.Parse(tem));
                    }
                    else {
                        while (chars.Count > 0)
                        {
                            if (!Operate(chars.Pop()))
                            {
                                return "ERROR";
                            }
                        }
                        chars.Push(s[i]);
                    }
                }
            }
            while (chars.Count > 0) {
                if (!Operate(chars.Pop()))
                {
                    return "ERROR";
                }
            }
            double result = Math.Round(nums.Pop(), 5);
            return result.ToString();
        }
        public bool Operate(char o)
        {
            double b=nums.Pop();
            double a=nums.Pop();
            if (o == '+')
                nums.Push(a + b);
            else if (o == '-')
                nums.Push(a - b);
            else if (o == '*')
                nums.Push(a * b);
            else
            {
                if (b == 0)
                    return false;
                    nums.Push(a / b);
                
            }
            return true;
        }
    }
}
